package de.idgard.android.addon.js;

import android.content.Context;
import android.util.Log;
import android.webkit.JsPromptResult;
import de.idgard.android.addon.services.ContextAware;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.services.BrowserUtilityService;

/**
 * @author pratik : android javascript bridge.
 * 
 */
public class IDGardJSHandler implements ContextAware {

	private static IDGardJSHandler instance = new IDGardJSHandler();

	public static IDGardJSHandler getInstance() {
		return instance;
	}

	private PrivacyConnect privacyConnect = new PrivacyConnect(); 

	private IDGardJSHandler() {

	}

	public void setContext(Context context) {
		privacyConnect.setContext(context);
	}

	private BrowserUtilityService getBrowserUtilityService() {
		return GlobalServiceRegistry.instance().getBrowserUtilityService();
	}

	private void getIDGardID(JsPromptResult result) {
		result.confirm(getBrowserUtilityService().getIDGardData().getIdgardId());
	}

	private void getJSessionID(JsPromptResult result) {
		result.confirm(getBrowserUtilityService().getIDGardData().getJsessionId());
	}

	/**
	 * handling idgard javascript...
	 * 
	 * @param message
	 * @param defaultValue
	 * @param result
	 */
	public void handleIDGardJs(String message, String defaultValue, JsPromptResult result) {
		String msgs[] = message.split(":");

		if (msgs.length == 2) {
			String command = msgs[1];
			Log.d("command", "" + command);

			if (command.equalsIgnoreCase("getIDGardID")) {
				getIDGardID(result);
			}
			else if (command.equalsIgnoreCase("getJSessionID")) {
				getJSessionID(result);
			}
			else if (command.equalsIgnoreCase("enableOneClickLogin")) {
				privacyConnect.enableOneClickLogin(defaultValue, result);
			}
			else if (command.equalsIgnoreCase("formWillSubmit")) {
				privacyConnect.formWillSubmit(defaultValue, result);
			}
			else if (command.equalsIgnoreCase("isOneClickEnabled")) {
				privacyConnect.isOneClickEnabled(result);
			}
			else if (command.equalsIgnoreCase("selectProfile")) {
				privacyConnect.selectProfile(defaultValue, result);
			}
			else if (command.equalsIgnoreCase("saveProfile")) {
				privacyConnect.saveProfile(defaultValue, result);
			}
		}
	}

}
